package com.robusta.cityuate.activities;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentMenuActivity;
import com.robusta.cityuate.objects.User;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.Token;

public class UserProfileActivity extends CityuateFragmentMenuActivity {

	public static final String TAG = UserProfileActivity.class.getName();
	public static final String RATE_TAG = UserProfileActivity.class.getName()
			+ "_RATE";
	// private ProgressDialog dialog;
	private Context mContext = this;
	User user;

	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			Log.d(TAG, "user data received success");
			getUserSuccess();
			ConnectionUtils.clearConnection(mContext, TAG);
		}

		@Override
		public void onFailure() {
			Log.d(TAG, "user data received fail");

			getUserFail();
			ConnectionUtils.clearConnection(mContext, TAG);
		}

		@Override
		public void onCancel() {
			progressBar.setVisibility(View.INVISIBLE);
			retry.setVisibility(View.VISIBLE);
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, TAG);
			finish();
		}
	};

	private CityuateBroadCastReceiver rateReceiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			Log.d(TAG, "user rated success");
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, RATE_TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, RATE_TAG);
			setSupportProgressBarIndeterminateVisibility(false);
		}

		@Override
		public void onFailure() {
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, RATE_TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, RATE_TAG);
			setSupportProgressBarIndeterminateVisibility(false);

		}

		@Override
		public void onCancel() {

			setSupportProgressBarIndeterminateVisibility(false);
		}
	};
	private TextView firstNameField;
	private TextView lastNameField;
	private TextView userNameField;
	private TextView emailField;
	private TextView dateofbirthField;
	private TextView mobileField;
	private TextView zipCodeField;
	private TextView countryField;
	private TextView cityField;
	private TextView districtField;
	private TextView buildNumField;
	private TextView streetField;
	private ProgressBar progressBar;
	private Button retry;
	private View profile_data;
	private RatingBar rateUser;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_profile_view);

		Log.e(TAG, "onCreate");
		// load components
		firstNameField = (TextView) findViewById(R.id.firstname);
		lastNameField = (TextView) findViewById(R.id.lastname);
		userNameField = (TextView) findViewById(R.id.usrname);
		emailField = (TextView) findViewById(R.id.email);
		dateofbirthField = (TextView) findViewById(R.id.dateofbirth);
		mobileField = (TextView) findViewById(R.id.mobilnum);
		zipCodeField = (TextView) findViewById(R.id.zipcode);
		countryField = (TextView) findViewById(R.id.country);
		cityField = (TextView) findViewById(R.id.city);
		districtField = (TextView) findViewById(R.id.district);
		buildNumField = (TextView) findViewById(R.id.buildnum);
		streetField = (TextView) findViewById(R.id.street);
		rateUser = (android.widget.RatingBar) findViewById(R.id.rate_user);

		rateUser.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				user.rate(mContext, rating);
			}
		});

		if (user != null && Token.getUserID(mContext) == user.getId())
			rateUser.setEnabled(false);
		progressBar = (ProgressBar) findViewById(R.id.profile_loading);
		retry = (Button) findViewById(R.id.retry);
		profile_data = findViewById(R.id.profile_data);
		user = (User) getIntent().getSerializableExtra(User.USER);

		ConnectionUtils.clearConnection(this, TAG);
		ConnectionUtils.clearConnection(this, RATE_TAG);

	}

	private void getUserData() {
		if (user == null) {

			User.getCurrentUserProfile(this, Token.getUserID(this));
			// // Start loading dialog and connecting variables
			progressBar.setVisibility(View.VISIBLE);
			profile_data.setVisibility(View.GONE);
			setSupportProgressBarIndeterminateVisibility(true);
		} else
			getUserSuccess();

	}

	@Override
	protected void onDestroy() {
		Log.e(TAG, "onDestroy");
		super.onDestroy();

		ConnectionUtils.clearConnection(this, TAG);

		ConnectionUtils.clearConnection(this, RATE_TAG);

	}

	@Override
	protected void onPause() {
		unregisterReceiver(receiver);
		unregisterReceiver(rateReceiver);
		Log.e(TAG, "onPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(TAG));
		registerReceiver(rateReceiver, new IntentFilter(RATE_TAG));
		Log.e(TAG, "onResume");

		if (ConnectionUtils.isConnecting(this, TAG)) {
			// showLoadingDialog();
			setSupportProgressBarIndeterminateVisibility(true);
		} else if (ConnectionUtils.wasConnected(this, TAG))
			if (ConnectionUtils.isResultSuccessful(this, TAG))
				getUserSuccess();
			else
				getUserFail();
		else
			getUserData();

		if (ConnectionUtils.isConnecting(this, RATE_TAG))
			setSupportProgressBarIndeterminateVisibility(true);
		else if (ConnectionUtils.wasConnected(this, RATE_TAG))
			if (ConnectionUtils.isResultSuccessful(this, RATE_TAG))
				rateReceiver.onSuccess();
			else
				rateReceiver.onFailure();

	}

	private void getUserSuccess() {

		setSupportProgressBarIndeterminateVisibility(false);
		if (user == null) {
			String userString = ConnectionUtils.getExtra(this, TAG);
			try {
				user = User.fromJSON(new JSONObject(userString));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		// fill fields with data
		firstNameField.setText(user.getFirst_name());
		lastNameField.setText(user.getLast_name());
		userNameField.setText(user.getUsername());
		emailField.setText(user.getEmail());
		dateofbirthField.setText(user.getDob());
		mobileField.setText(user.getMobile_number());
		zipCodeField.setText(user.getZip_code());
		countryField.setText(user.getCountry_name());
		cityField.setText(user.getCity());
		districtField.setText(user.getDistrict());
		buildNumField.setText(user.getBuilding_number());
		streetField.setText(user.getStreet());
		rateUser.setRating((float) user.getRate());

		progressBar.setVisibility(View.GONE);
		profile_data.setVisibility(View.VISIBLE);
		getSupportActionBar().setTitle(
				user.getFirst_name() + " " + user.getLast_name());
		getSupportActionBar().setTitle(R.string.user_profile);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.user_profile_option_menu, menu);
		if (user != null && Token.getUserID(mContext) != user.getId())
			menu.removeItem(R.id.edit);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.edit:
			Intent editActivity = new Intent(mContext,
					EditUserProfileActivity.class);
			editActivity.putExtra(TAG + "." + User.USER, user);
			startActivityForResult(editActivity,
					EditUserProfileActivity.EDIT_ACTIVITY_CODE);
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void getUserFail() {
		progressBar.setVisibility(View.GONE);
		retry.setVisibility(View.VISIBLE);
		setSupportProgressBarIndeterminateVisibility(false);
		// show failure message
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == EditUserProfileActivity.EDIT_ACTIVITY_CODE) {

			if (resultCode == RESULT_OK) {
				user = null;
				getUserData();
			}
		}

	}

	public void retryLoading(View v) {
		v.setVisibility(View.GONE);
		getUserData();
	}
}
